<?php
/**
 * 融云消息相关接口
 */

namespace app\api\controller;
use think\Db;
use \rongcloud\RongCloud;
use Exception;

/**
 * 群成员禁言
 * 敏感词
 * 用户添加黑名单都可以后期加入
 *
 */

class Rong extends Common
{
    public function __construct() //Db::connect('database_app');
    {
        $this->db_app = Db::connect('database_app');
        include VENDOR_PATH.'rongcloud/RongCloud.php';
        // 获取key和secret
        $key_secret=get_rong_key_secret();
        // 实例化融云
        $this->rong_cloud=new RongCloud($key_secret['key'],$key_secret['secret']);
    }

    // http://images2017.cnblogs.com/blog/422101/201711/422101-20171107114051044-2109099018.png

    /**
     * 获取token,
     * 创建和修改用户信息
     * 每次都会刷新token
     * 如果id存在，就修改用户和token信息
     * 如果id不存在，则添加新用户
     */
    public function getToken() {
        $userId = input('userId');
        $name = input('name');
        $portraitUri = input('portraitUri');

        $result_array = $this->rong_cloud->user()->getToken($userId, $name, $portraitUri);
        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }


    /**
     * 刷新用户信息
     * name和portraitUri非比传
     * 不传name和uri，名称和头像会被清空
     */
    public function refresh() {
        $userId = input('userId');
        $name = input('name');
        $portraitUri = input('portraitUri');

        $result_array = $this->rong_cloud->user()->refresh($userId, $name, $portraitUri);
        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    /**
     * 检查用户是否在线
     *
     */
    public function checkOnline() {
        $userId = input('userId');

        $result_array = $this->rong_cloud->user()->checkOnline($userId);
        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    /**
     * 发送私有消息
     * 可以发送给一个人，也可以发送给多个人
     * 文本消息 RC:TxtMsg  {"content":"hello","extra":"helloExtra"}
     * 图片消息 RC:ImgMsg  {"content":"ergaqreg", "imageUri":"http://images2017.cnblogs.com/blog/422101/201711/422101-20171107114051044-2109099018.png","extra":"helloExtra"}
     * 语音消息 RC:VcMsg
     * 图文消息	RC:ImgTextMsg
     * 位置消息	RC:LBSMsg
     * 添加联系人消息	RC:ContactNtf  {"operation":"op1","sourceUserId":"24","targetUserId":"21","message":"haha"
    ,"extra":"helloExtra"}
     * 通用命令通知消息	RC:CmdNtf	{"name":"AtPerson","data":"{\"sourceId\":\"9527\"}"}
     * 群组通知消息	RC:GrpNtf	{"operatorUserId":"4324","operation":"Rename","data":"{\"operatorNickname\":\"李天\",\"targetGroupName\":\"群名\"}","message":"修改本群名为本地生活","extra":""}
     * 命令消息	RC:CmdMsg	{"name":"AtPerson","data":"{\"sourceId\":\"9527\"}"}
     */
    public function publishPrivate() {
        $fromUserId = input('fromUserId');
        $toUserId   = input('toUserId');
        $objectName  = input('objectName');
        $content  = input('content');

        $content = array();
        $content['content'] = "hello";
        $content['extra']   = array("globalId"=>18360174986);
        $content = json_encode($content);

        $result_array = $this->rong_cloud->message()->publishPrivate('7384', ["16"], 'RC:TxtMsg',$content,"","","",0,0,0,1);

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }


    /**
     * 发送系统消息
     */
    public function PublishSystem() {
        $fromUserId = input('fromUserId');
        $toUserId   = input('toUserId');
        $objectName  = input('objectName');
        $content  = input('content');

        $content = array();
        $content['content'] = "hello";
        $content['extra']   = array("globalId"=>18360174986);
        $content = json_encode($content);

        $result_array = $this->rong_cloud->message()->PublishSystem('1', ["16"], 'RC:TxtMsg',$content, 'thisisapush', '{\"pushData\":\"hello\"}', '0', '0');

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    /**
     * 发送群消息
     * 允许向多个群发送消息，最多三个
     * 不过需求用不到多个群发
     */
    public function publishGroup() {
        $fromUserId = input('fromUserId');
        $toUserId   = input('toUserId');
        $objectName  = input('objectName');
        $content  = input('content');

        // 发送群组消息方法（以一个用户身份向群组发送消息，单条消息最大 128k.每秒钟最多发送 20 条消息，每次最多向 3 个群组发送，如：一次向 3 个群组发送消息，示为 3 条消息。）
        $result_array = $this->rong_cloud->message()->publishGroup('16', ["181"], 'RC:TxtMsg',"{\"content\":\"hello\",\"extra\":\"helloExtra\"}", 'thisisapush', '{\"pushData\":\"hello\"}', '1', '1', '0');

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    /**
     * 获取历史记录下载地址
     */
    public function getHistory() {
        // 消息历史记录下载地址获取 方法消息历史记录下载地址获取方法。获取 APP 内指定某天某小时内的所有会话消息记录的下载地址。（目前支持二人会话、讨论组、群组、聊天室、客服、系统通知消息历史记录下载）
        $result_array = $this->rong_cloud->message()->getHistory('2017111611');

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }

    }

    /**
     * 创建群组
     * 已存在的话，如果群成员有新的，就会添加进入群中。
     * 之前的群成员，只多不少。
     */
    public function createGroup() {
        // 创建群组方法（创建群组，并将用户加入该群组，用户将可以收到该群的消息，同一用户最多可加入 500 个群，每个群最大至 3000 人，App 内的群组数量没有限制.注：其实本方法是加入群组方法 /group/join 的别名。）
        $result_array = $this->rong_cloud->group()->create(["3","4","5"], '2', '测试2群');

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    /**
     * 刷新群组方法
     * 只有一个作用，就是更新群名称
     */
    public function refreshGroup() {
        // 刷新群组信息方法
        $result_array = $this->rong_cloud->group()->refresh('2', '新的测试2群');

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    /**
     * 将用户加入群组，类似于拉人进入群中
     * 如果群名称变了，会被修改
     * 如果群id不存在，将会创建群
     * 融云中并不存在群主的概念
     */
    public function joinGroup() {
        // 将用户加入指定群组，用户将可以收到该群的消息，同一用户最多可加入 500 个群，每个群最大至 3000 人。
        $result_array = $this->rong_cloud->group()->join(["7","8"], '1000', '测试1000群');

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    /**
     * 查询群成员
     * 查询出的只有群用户id
     */
    public function queryGroupUser() {
        // 查询群成员方法
        $result_array = $this->rong_cloud->group()->queryUser('2');

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    /**
     * 退群
     * 单个人退群
     * 多个人退群
     * 将人从群中移除
     */
    public function quitGroup() {
        // 退出群组方法（将用户从群中移除，不再接收该群组的消息.）
        $result_array = $this->rong_cloud->group()->quit(["3","4","5"], '2');

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    /**
     * 解散群
     * userId 表示群主，其实传啥都无所谓，群都会消失
     */
    public function dismissGroup() {
        // 解散群组方法。（将该群解散，所有用户都无法再接收该群的消息。）
        $result_array = $this->rong_cloud->group()->dismiss('7', '2');

        $result_array = json_decode($result_array, true);

        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            // 去除状态
            unset($result_array['code']);
            $this->outData['info'] = $result_array;
            return $this->outData;
        }else if ($result_array['code']==99){
            $this->outData['code'] = 99;
            $this->outData['message'] = $result_array['message'];
            return $this->outData;
        } else {
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }


    /******************************  其他方法  **********************************/
    // 获取 Token 方法
    public function get_token()
    {
        $userid = input('userid');
        // 从数据库中获取token
        $token = $this->db_app->table('genericattribute') -> where('Key','RongRoken') -> where('EntityId',$userid) -> find();
        if($token){
            $this->outData['data'] = $token['Value'];
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }
    // 刷新用户信息方法
    public function refresh_userinfo()
    {
        $userid = input('userid');
        // 获取用户昵称和头像
        $user_data = $this->db_app->table('genericattribute')
            -> alias('g')
            -> join('yunlutong.customer c','g.EntityId = c.Id')
            -> field('c.NickName,g.Value as headPic')
            -> where('g.EntityId',$userid)
            -> where('g.Key','Avatar')
            -> select();
        // 获取头像url格式
        $avatar=$user_data[0]['headPic'];
        // 更新融云用户头像
        $result_json=$this->rong_cloud->user()->refresh($userid,$user_data[0]['NickName'],$avatar);
        $result_array=json_decode($result_json,true);//json_decode 第二个参数为true，将返回数组而非object
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }


    // 封禁用户方法（每秒钟限 100 次）用户id  userid  minute  封禁时长  分钟
    public function block()
    {
        $userid = input('userid');
        $minute = input('minute');
        $result = $this->rong_cloud->user()->block($userid,$minute);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "封禁成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "封禁失败";
            return $this->outData;
        }
    }

    // 解除用户封禁方法（每秒钟限 100 次）
    public function unBlock()
    {
        $userid = input('userid');
        $result = $this->rong_cloud->user()->unBlock($userid);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "解封成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "解封失败";
            return $this->outData;
        }
    }

    // 获取被封禁用户方法（每秒钟限 100 次）userId  String  被封禁用户 ID。blockEndTime   String  封禁结束时间。
    public function queryBlock()
    {
        $result = $this->rong_cloud->user()->queryBlock();
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $data = $result_array['users'];
            $newData = array();
            foreach($data as $k => $v){
                $newData[$k] = getNIckHeadpic($v['userId']);
                $newData[$k]['blockEndTime'] = $v['blockEndTime'];
            }
            $this->outData['data'] = $newData;
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    // 添加用户到黑名单方法（每秒钟限 100 次）用户Id userid  被加黑的用户Id blackuserid
    public function addBlacklist()
    {
        $userid = input('userid');
        $blackuserid = input('blackuserid/a');
        $result = $this->rong_cloud->user()->addBlacklist($userid,$blackuserid);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    // 获取某用户的黑名单列表方法（每秒钟限 100 次）
    public function queryBlacklist()
    {
        $userid = input('userid');
        $result = $this->rong_cloud->user()->queryBlacklist($userid);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $info = $this->db_app->table('genericattribute')
                -> alias('g')
                -> join('yunlutong.customer c','g.EntityId = c.Id')
                -> field('c.Id,c.NickName,g.Value as headPic')
                -> where('g.EntityId','in',$result_array['users'])
                -> where('g.Key','Avatar')
                -> select();
            $this->outData['data'] = $info;
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    // 从黑名单中移除用户方法（每秒钟限 100 次）
    public function removeBlacklist()
    {
        $userid = input('userid');
        $blackuserid = input('blackuserid');
        $result = $this->rong_cloud->user()->removeBlacklist($userid,$blackuserid);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }




    // 同步用户所属群组方法
    public function sync()
    {
        $userId = input('userId');
        $groupInfo = input('groupInfo/a');
        $result = $this->rong_cloud->group()->sync($userId,$groupInfo);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    // 刷新群组信息方法
    public function refresh_group()
    {
        $groupId = input('groupId');
        $groupName = input('groupName');
        $result = $this->rong_cloud->group()->refresh($groupId,$groupName);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }

    // 将用户加入指定群组
    public function join_group()
    {
        $userId = input('userId/a');
        $groupId = input('groupId');
        $groupName = input('groupName');
        $result = $this->rong_cloud->group()->join($userId,$groupId,$groupName);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }




    // 添加禁言群成员
    public function addGagUser()
    {
        $userId = input('userId/a');
        $groupId = input('groupId');
        $minute = input('minute');
        $result = $this->rong_cloud->group()->addGagUser($userId,$groupId,$minute);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }
    // 查询被禁言群成员
    public function lisGagUser() //返回参数 time    String  解禁时间。userId  String  群成员 Id
    {
        $groupId = input('groupId');
        $result = $this->rong_cloud->group()->lisGagUser($groupId);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $data = $result_array['users'];
            $newData = array();
            foreach($data as $k => $v){
                $newData[$k] = getNIckHeadpic($v['userId']);
                $newData[$k]['time'] = $v['time'];
            }
            $this->outData['data'] = $newData;
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }
    // 移除禁言群成员
    public function rollBackGagUser()
    {
        $userId = input('userId/a');
        $groupId = input('groupId');
        $result = $this->rong_cloud->group()->rollBackGagUser($userId,$groupId);
        $result_array=json_decode($result,true);
        if ($result_array['code']==200) {
            $this->outData['code'] = 1;
            $this->outData['message'] = "操作成功";
            return $this->outData;
        }else{
            $this->outData['code'] = 2;
            $this->outData['message'] = "操作失败";
            return $this->outData;
        }
    }




}